package com.ayz.gateway.core.rpc.dubbo;

import cn.hutool.log.Log;

import com.ayz.gateway.core.rpc.GenericReferenceProxy;
import lombok.Data;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.dubbo.rpc.service.GenericService;

import java.lang.reflect.Method;

/**
 * @ClassName DubboGenericReferenceProxy
 * @Description TODO
 * @Author 快乐的星球
 * @Date 2023/5/6 20:07
 * @Version 1.0
 **/
@Data
public class DubboGenericReferenceProxy implements GenericReferenceProxy {

    private final Log log=Log.get(DubboGenericReferenceProxy.class);
    public static final String SYNC_CALL_METHOD_NAME="callSync";

    public static final String ASYNC_CALL_METHOD_NAME="callAsync";
    /**
     * 提供Dubbo范化调用的API
     */
    private GenericService genericService;
    /**
     * RPC资源方法名称
     */
    private String rpcMethod;

    public DubboGenericReferenceProxy(GenericService genericService, String rpcMethod) {
        this.genericService = genericService;
        this.rpcMethod = rpcMethod;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        //根据方法的名称判断是同步调用还是异步调用
        if(method.getName().equals(SYNC_CALL_METHOD_NAME)){
            //TODO: 处理同步调用
            Object[] args=(Object[]) objects[0];
            String[] parameterTypeNames=(String[]) objects[1];
            //发起调用
            return genericService.$invoke(rpcMethod, parameterTypeNames,args);
        }else if(method.getName().equals(ASYNC_CALL_METHOD_NAME)){
            //TODO: 处理异步调用
            Object[] args=(Object[]) objects[0];
            String[] parameterTypeNames=(String[]) objects[1];
            //发起异步调用
            return genericService
                    .$invokeAsync(rpcMethod, parameterTypeNames, args);
        }
        return null;
    }
}
